package com.epro.dx.activity.chagepassword;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

public class ChangePasswordActivity extends BaseFragmentActivity implements
		OnFocusChangeListener {
	private EditText oldPwd, newPwd, confirmPwd;
	private TextView changePwdEmail;

	private Button changePwdBtn;

	private String newPwdStr, oldPwdStr, confirmPwdStr, customerid;

	private String myOldPassWord;

	private ImageView oldOkIV, confirmOkIV;
	private Tracker tracker;
	
	private LinearLayout contentLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 //集成GA
        tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
        tracker.setScreenName("ChangePassword");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_change_password);
		setTitleContent(R.string.change_pwd_title);
		setLeftBtnContent(true, -1);
		intView();
		setListenner();
		myOldPassWord = StringUtil.getConfig(
				ServerConstant.Parameter.PARAMETER_NAME_USER_PWD, "");
		changePwdBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				getData();
				if (checkPwd()) {
					AsyncTaskUtil.executeTask(new ChangePwdAysncTask());
				}
			}
		});
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
	}

	/**
	 * 初始化控件
	 */
	private void intView() {
		contentLayout=(LinearLayout) findViewById(R.id.content_layout);
		changePwdBtn = (Button) findViewById(R.id.change_pwd_btn);
		oldPwd = (EditText) findViewById(R.id.change_pwd_old_pwd);
		newPwd = (EditText) findViewById(R.id.change_pwd_new_pwd);
		confirmPwd = (EditText) findViewById(R.id.change_pwd_confirm_pwd);
		changePwdEmail = (TextView) findViewById(R.id.change_pwd_email);
		oldOkIV = (ImageView) findViewById(R.id.old_pwd_ok);
		confirmOkIV = (ImageView) findViewById(R.id.confirm_pwd_ok);
		setEmail();
	}

	private void setListenner() {
		oldPwd.setOnFocusChangeListener(this);
		oldPwd.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				oldPwdStr=s.toString().trim();
				if (null!=myOldPassWord&&!"".equals(myOldPassWord)&&myOldPassWord.equals(oldPwdStr)) {
					oldOkIV.setVisibility(View.VISIBLE);
				} else {
					oldOkIV.setVisibility(View.GONE);
				}
				setSubmitButtonState();
			}
		});
		newPwd.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				newPwdStr=s.toString().trim();
				if(newPwdStr!=null&&!"".equals(newPwdStr)&&newPwdStr.equals(confirmPwdStr)){
					confirmOkIV.setVisibility(View.VISIBLE);
				} else {
					confirmOkIV.setVisibility(View.GONE);
				}
				setSubmitButtonState();
			}
		});
		confirmPwd.setOnFocusChangeListener(this);
		confirmPwd.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				confirmPwdStr = s.toString().trim();
				if (null!=newPwdStr&&!"".equals(newPwdStr)&&newPwdStr.equals(confirmPwdStr)) {
					confirmOkIV.setVisibility(View.VISIBLE);
				} else {
					confirmOkIV.setVisibility(View.GONE);
				}
				setSubmitButtonState();
			}
		});
	}

	/**
	 * 设置邮箱
	 */
	private void setEmail() {
		String email = StringUtil.getConfig(
				ServerConstant.Parameter.PARAMETER_NAME_USER_EMAIL, "");
		changePwdEmail.setText(email);
	}

	/**
	 * 获取数据
	 */
	private void getData() {
		customerid = GlobalConfig.getInstance().getUserSessionCfg()
				.getCustomerid();
		if (null == customerid || "".equals(customerid)) {
			customerid = StringUtil.getConfig(
					ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
		}

		oldPwdStr = oldPwd.getText().toString().trim();
		newPwdStr = newPwd.getText().toString().trim();
		confirmPwdStr = confirmPwd.getText().toString().trim();
	}

	/**
	 * 验证密码规范
	 * 
	 * @return
	 */
	private boolean checkPwd() {
		InputMethodManager imm = (InputMethodManager) getApplicationContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(changePwdBtn.getWindowToken(), 0);
		if (TextUtils.isEmpty(oldPwdStr)) {
			AlertToast.alert(ChangePasswordActivity.this,
					R.string.user_login_validate_pwd_is_null, 10000);
			return false;
		} else if (!oldPwdStr.equals(myOldPassWord)) {
			AlertToast.alert(
					ChangePasswordActivity.this,
					getString(R.string.old_pwd_is_wrong), 1000);
			return false;
		}else if (TextUtils.isEmpty(newPwdStr)) {
			AlertToast.alert(ChangePasswordActivity.this,
					R.string.user_login_validate_new_pwd_is_null, 1000);
			return false;
		}else if(null!=newPwdStr&&newPwdStr.contains(" ")){
			AlertToast.alert(ChangePasswordActivity.this,
					R.string.pwd_not_space, 0);
			return false;
		}else if (newPwdStr.length() < Constant.Rule.PWD_MIN_LENGTH
				|| newPwdStr.length() > Constant.Rule.PWD_MAX_LENGTH) {
			AlertToast.alert(
					ChangePasswordActivity.this,
					getString(R.string.change_pwd_length_error,
							Constant.Rule.PWD_MIN_LENGTH,
							Constant.Rule.PWD_MAX_LENGTH), 1000);
			return false;
		} else if (oldPwdStr.equals(newPwdStr)) {
			AlertToast.alert(ChangePasswordActivity.this,
					getString(R.string.change_old_new_pwd_error), 1000);
			return false;
		} else if (!(newPwdStr.equals(confirmPwdStr))) {
			AlertToast.alert(ChangePasswordActivity.this,
					getString(R.string.change_re_new_pwd_error), 1000);
			return false;
		}
		return true;
	}

	/**
	 * 等待进度条
	 * 
	 * @version [版本号, 2013-3-14]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 * 
	 * @author hf
	 */

	protected class ChangePwdAysncTask extends BaseNeedReLoginTask {

		@Override
		protected void onPreExecute() {
			// ((MyAccountActivity)
			// getActivity()).asyncActivityImpl.showProgressDialog();
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {

			try {
				ProviderFactory.createUserServiceProvider().changePassword(
						customerid, oldPwdStr, newPwdStr,ActivityUtil.getCustomerToken());
				
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("ChangePasswordFragment", "Loading", e);
			}

			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				hideAllLayout(contentLayout);
				if ("0".equals(result)) {
                    StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_IS_LOGIN, "false");
					if("1".equals(StringUtil.getConfig(getApplicationContext(), ServerConstant.Parameter.PARAMETER_NAME_USER_IS_REMEBER))){
						 StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_USER_IS_REMEBER, "0");
					}
                    AlertToast.alert(
							ChangePasswordActivity.this,
							getResources().getString(
									R.string.change_password_success));
                    Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
					intent.putExtra("changePwd", true);
                    startActivity(intent);
					finish();
				} else if(!isRelogin){
					AlertToast.alert(ChangePasswordActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
				// ((MyAccountActivity)
				// getActivity()).asyncActivityImpl.dismissProgressDialog();

			}

		}

		@Override
		protected Context setContext() {
			return ChangePasswordActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new ChangePwdAysncTask();
		}

	}

	@Override
	public void onFocusChange(View view, boolean isFocus) {
		switch (view.getId()) {
//		case R.id.change_pwd_old_pwd:
//			if (!isFocus) {
//				oldPwdStr = oldPwd.getText().toString().trim();
//				if (myOldPassWord.equals(oldPwd)) {
//					oldOkIV.setVisibility(View.VISIBLE);
//				} else {
//					oldOkIV.setVisibility(View.GONE);
//				}
//			}
//			break;
//		case R.id.change_pwd_confirm_pwd:
//			if (!isFocus) {
//				newPwdStr = newPwd.getText().toString().trim();
//				confirmPwdStr = confirmPwd.getText().toString().trim();
//				if (newPwd.equals(confirmPwdStr)) {
//					confirmOkIV.setVisibility(View.VISIBLE);
//				} else {
//					confirmOkIV.setVisibility(View.GONE);
//				}
//			}
//
//			break;

		default:
			break;
		}
	}
	/**
	 * @创建：Tony 2016-4-22下午3:56:21
	 * @描述：设置提交按钮的状态
	 */
	private void setSubmitButtonState(){
		if(TextUtils.isEmpty(confirmPwdStr) || TextUtils.isEmpty(oldPwdStr) || TextUtils.isEmpty(newPwdStr)){
			changePwdBtn.setBackgroundResource(R.drawable.bg_btn_gray);
			changePwdBtn.setTextColor(Color.parseColor("#999999"));
		}else{
			changePwdBtn.setBackgroundResource(R.drawable.selector_bg_btn_gray);
			changePwdBtn.setTextColor(Color.BLACK);
		}
	}
}
